package com.mftour.moudles.controller;

import java.io.File;
import java.util.Date;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.mftour.common.Constant;
import com.mftour.common.utils.FtpClientUtil;
import com.mftour.common.utils.GetProperty;
import com.mftour.common.utils.JsonUtil;
import com.mftour.moudles.entity.User;
import com.mftour.moudles.vo.AjaxResponse;

@Controller
@RequestMapping(value = "pic")
public class PicController extends BaseController {

	/**
	 * 渠道管理首页
	 * 
	 * @param model
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "index")
	public String index() {
		return "test";
	}

	/**
	 * @see 上传图片
	 * @param picType
	 *            图片类型 1客栈图片,2房型图片,3其他
	 * @return
	 * @throws Exception
	 */
	@ResponseBody
	@RequestMapping(value = "/upload/{picType}", method = RequestMethod.POST,produces=Constant.MEDIA_APPLICATION_JSON)
	public String step(@PathVariable String picType,@RequestParam("file") MultipartFile file) throws Exception {
		try {
			User longinUser = (User) session.getAttribute(Constant.SESSION_LOGIN_USER);// 当前登录用户
			String path = GetProperty.GetConfPath(null);
			String host = GetProperty.readValue(path, "ftpHost");
//			String picUrl=GetProperty.readValue(path, "picUrl");
			int port = Integer.parseInt(GetProperty.readValue(path, "ftpPort"));
			String username = GetProperty.readValue(path, "username");
			String password = GetProperty.readValue(path, "password");
//			String picPrefix=GetProperty.readValue(path, "picPrefix");
			
//			File uploadFile = new File(picUrl + "/" + longinUser.getUserId()); // 图片存放位置
//			if (!uploadFile.exists()){
//				System.out.println(uploadFile.mkdirs());
//			}
			String suffix = file.getOriginalFilename().substring  
					(file.getOriginalFilename().lastIndexOf(".")); 
//			file.transferTo(new File(uploadFile,String.valueOf(new Date().getTime())+suffix));
			
			String filename = String.valueOf(new Date().getTime()) + suffix;
			String dir = picType;
			
			FtpClientUtil.sendFile(host, port, username, password, dir, filename, file.getInputStream());
			AjaxResponse ajaxResponse = new AjaxResponse();
			return JsonUtil.writeValueAsString(ajaxResponse);
		} catch (Exception e) {
			AjaxResponse ajaxResponse = new AjaxResponse();
			ajaxResponse.setCode(Constant.RS_CODE_ERROR);
			ajaxResponse.setMsg(Constant.RS_MSG_ERROR);
			return JsonUtil.writeValueAsString(ajaxResponse);
		} 
	}
}
